package com.qys.livesMall.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qys.livesMall.app.user.model.dto.sys.SysHomeStatisticsDTO;
import com.qys.livesMall.app.user.model.entity.H2AppUserRechargeWithdrawals;
import com.qys.livesMall.app.user.model.entity.UserStatisticsYesterdayInfo;
import com.qys.livesMall.app.user.model.vo.sys.SysHomeStatisticsVO;
import com.qys.livesMall.app.user.model.vo.sys.SysHomeTodayStatisticsVO;
import com.qys.livesMall.app.user.service.IH2AppUserRechargeWithdrawalsService;
import com.qys.livesMall.app.user.service.IH2AppUserService;
import com.qys.livesMall.app.user.service.UserStatisticsYesterdayInfoService;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import com.qys.livesMall.finance.service.FinanceShopAccountService;
import com.qys.livesMall.finance.service.FinanceUserAccountService;
import com.qys.livesMall.shop.dao.H2ShopRechargeWithdrawalDao;
import com.qys.livesMall.shop.mapper.H2ShopBaseMapper;
import com.qys.livesMall.shop.mapper.H2ShopRechargeWithdrawalMapper;
import com.qys.livesMall.shop.mapper.ShopOrderSkuMapper;
import com.qys.livesMall.shop.modal.entity.H2ShopBase;
import com.qys.livesMall.shop.modal.vo.ShopDailyDataVO;
import com.qys.livesMall.shop.service.SysHomeStatisticsService;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.time.LocalDateTime;

@Service
public class SysHomeStatisticsServiceImpl implements SysHomeStatisticsService {
    @Resource
    private UserStatisticsYesterdayInfoService userStatisticsYesterdayInfoService;
    @Resource
    private IH2AppUserRechargeWithdrawalsService rechargeWithdrawalsService;
    @Resource
    private H2ShopRechargeWithdrawalDao withdrawalDao;
    @Resource
    private FinanceShopAccountService shopAccountService;
    @Resource
    private FinanceUserAccountService financeUserAccountService;
    @Resource
    private IH2AppUserService ih2AppUserService;

    @Resource
    private H2ShopBaseMapper h2ShopBaseMapper;

    @Resource
    private H2ShopRechargeWithdrawalMapper h2ShopRechargeWithdrawalMapper;

    @Resource
    private ShopOrderSkuMapper shopOrderSkuMapper;

    public static final DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public SysHomeStatisticsVO info(SysHomeStatisticsDTO dto) {
        if (null == dto.getUserSysType()){
            dto.setUserSysType(1);
        }
        SysHomeStatisticsVO sysHomeStatisticsVO = new SysHomeStatisticsVO();
        //昨天统计的数据
        UserStatisticsYesterdayInfo yesterdayInfo = userStatisticsYesterdayInfoService.getToday(dto.getType(), dto.getUserSysType());
        if (null != yesterdayInfo) {
            BeanUtil.copyProperties(yesterdayInfo, sysHomeStatisticsVO);
        }
        SysHomeStatisticsVO vo = userStatisticsYesterdayInfoService.getListbyDatatime(dto);
        if (null != vo) {
            BeanUtil.copyProperties(vo, sysHomeStatisticsVO);
        }
        BigDecimal auditWithdrawal = BigDecimal.ZERO;
        BigDecimal initiateWithdrawal = BigDecimal.ZERO;
        BigDecimal totalBalance = BigDecimal.ZERO;
        if (dto.getType() == 0) {
            //待审核提现
            auditWithdrawal = rechargeWithdrawalsService.getAuditWithdrawal(dto);
            initiateWithdrawal = rechargeWithdrawalsService.getInitiateWithdrawal(dto.getUserSysType());
            totalBalance = financeUserAccountService.getTotalBalance(dto.getUserSysType());
        } else {
            auditWithdrawal = withdrawalDao.getAuditWithdrawal(dto);
            initiateWithdrawal = withdrawalDao.getInitiateWithdrawal(dto.getUserSysType());
            totalBalance = shopAccountService.getTotalBalance(dto.getUserSysType());
        }
        Integer activePeopleNumber = ih2AppUserService.getbyLastLoginTime(dto);
        sysHomeStatisticsVO.setWaitWithdrawal(auditWithdrawal);
        sysHomeStatisticsVO.setInitiateWithdrawal(initiateWithdrawal);
        sysHomeStatisticsVO.setTotalBalance(totalBalance);
        sysHomeStatisticsVO.setActivePeopleNumber(activePeopleNumber);
        return sysHomeStatisticsVO;
    }

    @Override
    public SysHomeTodayStatisticsVO todayInfo(Integer userSysType) {
        if (null == userSysType){
            userSysType=1;
        }
        SysHomeTodayStatisticsVO sysHomeTodayStatisticsVO=new SysHomeTodayStatisticsVO();
        //昨天统计用户的数据
        UserStatisticsYesterdayInfo yesterdayInfo=userStatisticsYesterdayInfoService.getToday(0, userSysType);
        Integer todayPeopleNumber= ih2AppUserService.getTodayPeopleNumber(userSysType);
        List<H2AppUserRechargeWithdrawals> rechargeWithdrawals=rechargeWithdrawalsService.getTodayData(userSysType);
        long rechargePeople=0L;
        long withdrawalPeople=0L;
        BigDecimal recharge=BigDecimal.ZERO;
        BigDecimal withdrawal=BigDecimal.ZERO;
        Integer totalRechargePeople =rechargeWithdrawalsService.gettotalRechargePeoplecount(userSysType);
        sysHomeTodayStatisticsVO.setTotalRechargePeople(totalRechargePeople);
        if (CollectionUtils.isNotEmpty(rechargeWithdrawals)){
            //充值金额
             recharge = rechargeWithdrawals.stream().filter(a -> a.getType().equals(AccountBusinessTypeEnum.RECHARGE.getType())).map(a -> a.getRealAmount()).reduce(
                    BigDecimal.ZERO, BigDecimal::add
            );
            //提现金额
            withdrawal = rechargeWithdrawals.stream().filter(a -> a.getType().equals(AccountBusinessTypeEnum.WITHDRAWAL.getType())).map(a -> a.getRealAmount()).reduce(
                    BigDecimal.ZERO, BigDecimal::add
            );
            rechargePeople=rechargeWithdrawals.stream().filter(a -> a.getType().equals(AccountBusinessTypeEnum.RECHARGE.getType())).map(H2AppUserRechargeWithdrawals::getUserId).distinct().count();

            withdrawalPeople=rechargeWithdrawals.stream().filter(a -> a.getType().equals(AccountBusinessTypeEnum.WITHDRAWAL.getType())).map(H2AppUserRechargeWithdrawals::getUserId).distinct().count();
        }
        if (null != yesterdayInfo){
            sysHomeTodayStatisticsVO.setYesterdayRegister(yesterdayInfo.getRegister());
            sysHomeTodayStatisticsVO.setTotalRegister(yesterdayInfo.getTotalRegister()+todayPeopleNumber);
            sysHomeTodayStatisticsVO.setTotalWithdrawalPeople((int) (yesterdayInfo.getTotalWithdrawalPeople()+withdrawalPeople));
            sysHomeTodayStatisticsVO.setTotalRecharge(yesterdayInfo.getTotalRecharge().add(recharge));
            sysHomeTodayStatisticsVO.setTotalWithdrawal(yesterdayInfo.getTotalWithdrawal().add(withdrawal));
        }else {
            sysHomeTodayStatisticsVO.setYesterdayRegister(0);
            sysHomeTodayStatisticsVO.setTotalRegister(todayPeopleNumber);
            sysHomeTodayStatisticsVO.setTotalWithdrawalPeople((int)withdrawalPeople);
            sysHomeTodayStatisticsVO.setTotalRecharge(recharge);
            sysHomeTodayStatisticsVO.setTotalWithdrawal(withdrawal);
        }
        sysHomeTodayStatisticsVO.setRegister(todayPeopleNumber);
        sysHomeTodayStatisticsVO.setWithdrawalPeople((int) withdrawalPeople);
        sysHomeTodayStatisticsVO.setRechargePeople((int) rechargePeople);
        sysHomeTodayStatisticsVO.setRecharge(recharge);
        sysHomeTodayStatisticsVO.setWithdrawal(withdrawal);
        return sysHomeTodayStatisticsVO;
    }

    @Override
    public ShopDailyDataVO getShopDailyData() {
        ShopDailyDataVO shopDailyDataVO = new ShopDailyDataVO();
//        今日新增店铺数量
        Integer addShopNum = getShopNum(LocalDateTime.now().format(format),1);
        shopDailyDataVO.setIncreaseShop(addShopNum);
//        店铺总数量
        Integer shopNum = getShopNum(null,1);
        shopDailyDataVO.setTotalShop(shopNum);

        setShopSellInfo(shopDailyDataVO,1);

        setShoChargeWithdrawal(shopDailyDataVO,1);

        return shopDailyDataVO;
    }

    private void setShopSellInfo(ShopDailyDataVO shopDailyDataVO,Integer type) {

        ShopDailyDataVO shopOrderData = shopOrderSkuMapper.getShopOrderData(LocalDateTime.now().format(format),type);
        //        店铺销量
        shopDailyDataVO.setShopSell(shopOrderData.getShopSell());
        //        店铺销售额
        shopDailyDataVO.setSalesVolume(shopOrderData.getSalesVolume());
        ShopDailyDataVO shopOrderTotalData = shopOrderSkuMapper.getShopOrderData(null,type);
        shopDailyDataVO.setTotalShopSell(shopOrderTotalData.getShopSell());
        shopDailyDataVO.setTotalSalesVolume(shopOrderTotalData.getSalesVolume());
    }

    private void setShoChargeWithdrawal(ShopDailyDataVO shopDailyDataVO,Integer type) {
//        todo 待优化
        ShopDailyDataVO data = h2ShopRechargeWithdrawalMapper.getShopRechargeWithdrawalData(LocalDateTime.now().format(format),type);
        //        店铺充值数量
        shopDailyDataVO.setShopCharge(data.getShopCharge());
        //        店铺充值人数
        shopDailyDataVO.setShopChargeNum(data.getShopChargeNum());
        //        店铺提现个数
        shopDailyDataVO.setShopWithdrawalNum(data.getShopWithdrawalNum());
//        todo 待优化
        ShopDailyDataVO totalData = h2ShopRechargeWithdrawalMapper.getShopRechargeWithdrawalData(null,type);
        //        店铺充值数量
        shopDailyDataVO.setTotalShopCharge(totalData.getShopCharge());
        //        店铺充值人数
        shopDailyDataVO.setTotalShopChargeNum(totalData.getShopChargeNum());
        //        店铺提现个数
        shopDailyDataVO.setTotalShopWithdrawalNum(totalData.getShopWithdrawalNum());
    }

    /**
     * 获取店铺数量
     * @param time
     * @return
     */
    private Integer getShopNum(String time,Integer type) {
        LambdaQueryWrapper<H2ShopBase> shopQuery = Wrappers.lambdaQuery(H2ShopBase.class);
        String condition = " where";
        if(type != null){
            shopQuery.eq(H2ShopBase::getType,type);
            condition = " and";
        }
        if (time != null) {
            shopQuery.last(condition+" TO_DAYS( create_time ) = TO_DAYS(\""+time+"\")");
        }
        return h2ShopBaseMapper.selectCount(shopQuery).intValue();
    }
}
